package com.LeeCode;

/**
 * 搜索插入位置
 */

public class Code035 {
    public static void main(String[] args) {
        int[] nums = {1, 3, 5, 6};
        int target = 2;

        System.out.println(new Code035().searchInsert1(nums, target));
    }

    // 二分查找
    public int searchInsert(int[] nums, int target) {
        int left = 0, right = nums.length - 1, mid;

        while (left <= right) {
            mid = (left + right) / 2;
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return left;
    }

    // 二分查找,开区间写法
    public int searchInsert1(int[] nums, int target) {
        int left = -1, right = nums.length, mid;
        while (left + 1 < right) {
            mid = left + (right - left) / 2;
            if (nums[mid] >= target) {
                right = mid;
            } else {
                left = mid;
            }
        }
        return right;
    }
}
